#coding:utf-8

import datetime;
import time
import os
import re
import urllib
import hashlib
import sys;
import sqlite3;
import imghdr;
import urllib.request
import socket
from xmlrpc.client import DateTime;
import json

import  udp_json_msg_def as MSG;

TARGET_PORT_UDP=7000
LOCAL_LISTEN_PORT_UDP=6667




addr_list={}
#------------server var----------------
udp_server_address=None
local_ip_str=""
def udp_recv_init(local_ip):
    print("udp bind ip->"+local_ip+"port="+str(LOCAL_LISTEN_PORT_UDP))
    if local_ip != "":
        udp_server_address=(local_ip,LOCAL_LISTEN_PORT_UDP)
    else:
        udp_server_address=('127.0.0.1',LOCAL_LISTEN_PORT_UDP)
        
    udp_server_skt=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    udp_server_skt.bind(udp_server_address)
    udp_server_skt.setblocking(False)
    return udp_server_skt;
def parse_udp_recv_data(udp_data):
    try:
        print("udp_data-->:")
        print(udp_data.decode())
        json_to_dict = json.loads(udp_data.decode())
        print(json_to_dict["msghead"])
        print(json_to_dict["version"])
        print(json_to_dict["ip_from"])
        print(json_to_dict["port_from"])
        #解析命令
        if json_to_dict["msghead"] == "custom" and json_to_dict["version"] == "1.1":
            if json_to_dict["ip_from"] != "" and json_to_dict["port_from"] != 0:
                seft_ip_str = "255.255.255.255"
                seft_ip_port = 9999
                if json_to_dict["cmd"] == "scan_dev":
                    msg_rspn_data = {"msghead": "custom",  "version": "1.1", "msgid": "custom",
                     "ip_addr": seft_ip_str, "port": seft_ip_port,"cmd": "scan_dev_resp", "dev_type":"light" , "list":[{"on"}]}
                    send_udp_msg(str(json_to_dict["ip_from"]), json_to_dict["port_from"],json.dumps(msg_rspn_data));
                elif json_to_dict["cmd"] == "set":
                    msg_rspn_data = {"msghead": "custom",  "version": "1.1", "msgid": "custom",
                     "ip_addr": seft_ip_str, "port": seft_ip_port, "cmd": "set_resp" , "dev_index":1, "value":"on"}
                    send_udp_msg(str(json_to_dict["ip_from"]), json_to_dict["port_from"],json.dumps(msg_rspn_data));
                elif json_to_dict["cmd"] == "get":
                    print("dd")
    except:
        print("recv data err="+udp_data)
    
def udp_server_recv(skt):
    # while 1:
    # print("recv poll")
    try:        
        data,addr=skt.recvfrom(2048)
        print( "got data from",addr)
        # print (data)
        parse_udp_recv_data(data)
    except:
        pass
def  get_self_addr():
    #获取本地的ip地址
    ipv4s=socket.gethostbyname_ex(socket.gethostname())[2]
    global local_ip_str
    local_ip_str = str(ipv4s[3])
    print("local ip="+ local_ip_str)

def  send_udp_msg(ip_addr, port, data_msg):        
    addr_target=(ip_addr,port) 
    sock_t=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    sock_t.sendto((data_msg).encode(), addr_target)
    sock_t.close()

def  main_poll():
    get_self_addr()
    skt_t = udp_recv_init(local_ip_str)
    index_t = 1;
    try:
        while True:
            udp_server_recv(skt_t);
            time.sleep(0.2);
    except KeyboardInterrupt:
        pass
    skt_t.close()

if __name__ == '__main__':
    # main_poll();

    msg_rspn_data1 = MSG.MSG_VAL_HD_ALL
    msg_body = {MSG.MSG_KEY_IP:"123.123.123.123", MSG.MSG_KEY_PORT:9999}
    msg_body.update(msg_rspn_data1)

    # msg_rspn_data1 = {MSG.K_HEAD:MSG.K_HEAD}
    print(msg_body)
